//
//  YYImageViewController.swift
//  CodeLibrary_Swift
//
//  Created by 陆文宇 on 2017/2/9.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit

class YYImageViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    let photos: Array<YYPhotoModel>
    var currentIndex: Int
    var isCommon = false
    
    let topView: UIView = {
        let _topView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 64))
        _topView.alpha = 0.5
        _topView.backgroundColor = UIColor.black
        return _topView
    }()
    let buttomView: UIView = {
        let _buttomView: UIView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - 49, width: UIScreen.main.bounds.size.width, height: 49))
        _buttomView.backgroundColor = UIColor.black
        _buttomView.alpha = 0.5
        return _buttomView
    }()
    
    let collectionView: UICollectionView = {
        let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 15
        flowLayout.minimumInteritemSpacing = 15
        flowLayout.itemSize = UIScreen.main.bounds.size
        flowLayout.scrollDirection = .horizontal
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15)
        
        let _collectionView: UICollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width + 15, height: UIScreen.main.bounds.size.height), collectionViewLayout: flowLayout)
        _collectionView.isPagingEnabled = true
        return _collectionView
    }()
    
    let chooseImageView: UIImageView = {
        let _chooseImageView: UIImageView = UIImageView(frame: CGRect(x: UIScreen.main.bounds.size.width - 47, y: 17, width: 30, height: 30))
        _chooseImageView.clipsToBounds = true
        _chooseImageView.layer.cornerRadius = 15
        _chooseImageView.layer.borderWidth = 1
        _chooseImageView.layer.borderColor = UIColor.white.cgColor
        return _chooseImageView
    }()
    let chooseLabel: UILabel = {
        let _chooseLabel: UILabel = UILabel(frame: CGRect(x: UIScreen.main.bounds.size.width - 47, y: 17, width: 30, height: 30))
        _chooseLabel.textAlignment = .center
        return _chooseLabel
    }()
    let endButton: UIButton = {
        let _endButton: UIButton = UIButton(type: .system)
        _endButton.frame = CGRect(x: UIScreen.main.bounds.size.width - 60, y: UIScreen.main.bounds.size.height - 40, width: 60, height: 40)
        _endButton.setTitle("完成", for: .normal)
        _endButton.setTitleColor(UIColor.white, for: .normal)
        return _endButton
    }()
    let backButton: UIButton = {
        let _backButton: UIButton = UIButton(type: .system)
        _backButton.frame = CGRect(x: 0, y: 0, width: 64, height: 64)
        let attributesDic = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17)]
        let backTitle: NSAttributedString = NSAttributedString(string: "返回", attributes: attributesDic)
        _backButton.setAttributedTitle(backTitle, for: .normal)
        return _backButton
    }()
    
    var chooseClosure: ((Int) -> Void)?
    var endClosure: (() -> Void)?
    init(photos: Array<YYPhotoModel>, currentIndex index: Int) {
        self.photos = photos
        self.currentIndex = index
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var prefersStatusBarHidden: Bool {
        return !isCommon && navigationController!.isNavigationBarHidden
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.black
        navigationController?.isNavigationBarHidden = !isCommon
        navigationController?.navigationBar.isTranslucent = true
        automaticallyAdjustsScrollViewInsets = false
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.contentOffset = CGPoint(x: (UIScreen.main.bounds.size.width + 15) * CGFloat(currentIndex), y: 0)
        
        collectionView.register(YYImageCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        
        backButton.addTarget(self, action: #selector(back(sender:)), for: .touchUpInside)
        endButton.addTarget(self, action: #selector(end(sender:)), for: .touchUpInside)
        
        let hiddenTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hideTapAction(sender:)))
        let chooseTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(chooseTapAction(sender:)))
        
        chooseLabel.isUserInteractionEnabled = true
        
        chooseLabel.addGestureRecognizer(chooseTap)
        view.addGestureRecognizer(hiddenTap)
        
        view.addSubview(collectionView)
        if !isCommon {
            view.addSubview(topView)
            view.addSubview(chooseImageView)
            view.addSubview(chooseLabel)
            view.addSubview(backButton)
            view.addSubview(buttomView)
            view.addSubview(endButton)
        }
        
        currentIndex = -1
        scrollViewDidScroll(collectionView)
        
        if YYPhotoCollectionViewCell.choosedCount > 0 {
            endButton.setTitle("完成(\(YYPhotoCollectionViewCell.choosedCount))", for: .normal)
        } else {
            endButton.setTitle("完成", for: .normal)
        }
    }
    
    @objc func end(sender: UIButton) -> Void {
        if YYPhotoCollectionViewCell.choosedCount == 0 {
            chooseTapAction(sender: nil)
        }
        endClosure!()
    }
    
    @objc func back(sender: UIButton) -> Void {
        let _ = navigationController?.popViewController(animated: true)
    }
    
    @objc func hideTapAction(sender: UITapGestureRecognizer) -> Void {
        if isCommon {
            navigationController?.isNavigationBarHidden = !navigationController!.isNavigationBarHidden
            setNeedsStatusBarAppearanceUpdate()
        } else {
            topView.isHidden = !topView.isHidden
            buttomView.isHidden = !buttomView.isHidden
            endButton.isHidden = !endButton.isHidden
            backButton.isHidden = !backButton.isHidden
            chooseLabel.isHidden = !chooseLabel.isHidden
            chooseImageView.isHidden = !chooseImageView.isHidden
        }
    }
    
    @objc func chooseTapAction(sender: UITapGestureRecognizer?) -> Void {
        let photo: YYPhotoModel = photos[currentIndex]
        if photo.chooseNumber == 0 {
            chooseLabel.text = "\(YYPhotoCollectionViewCell.choosedCount + 1)"
            chooseImageView.backgroundColor = UIColor.cyan
            chooseImageView.transform = CGAffineTransform(scaleX: 0, y: 0)
            UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
                self.chooseImageView.transform = CGAffineTransform(scaleX: 1, y: 1)
            }, completion: nil)
        } else {
            chooseLabel.text = nil
            chooseImageView.backgroundColor = UIColor.clear
        }
        chooseClosure!(currentIndex)
        
        if YYPhotoCollectionViewCell.choosedCount > 0 {
            endButton.setTitle("完成(\(YYPhotoCollectionViewCell.choosedCount))", for: .normal)
        } else {
            endButton.setTitle("完成", for: .normal)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: YYImageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! YYImageCollectionViewCell
        
        let photo: YYPhotoModel = photos[indexPath.item]
        cell.zoomImageView.scrollView.zoomScale = 1
        cell.zoomImageView.imageView.image = photo.image
        let height = screenWidth / photo.image.size.width * photo.image.size.height
        cell.zoomImageView.imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: height)
        if height < screenHeight {
            let maxZoomScale = screenHeight / height
            cell.zoomImageView.scrollView.maximumZoomScale = maxZoomScale > 2 ? maxZoomScale : 2
            cell.zoomImageView.imageView.center = CGPoint(x: screenWidth / 2, y: screenHeight / 2)
        }
        DispatchQueue.global().async {
            let originalImage: UIImage = photo.originalImage
            DispatchQueue.main.async {
                cell.zoomImageView.imageView.image = originalImage
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        (cell as! YYImageCollectionViewCell).zoomImageView.scrollView.zoomScale = 1
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let index: Int = Int(scrollView.contentOffset.x / (scrollView.frame.size.width / 2))
        if currentIndex != (index + 1) / 2 {
            currentIndex = (index + 1) / 2
            title = "\(currentIndex + 1)/\(photos.count)"
            let photo: YYPhotoModel = photos[currentIndex]
            if photo.chooseNumber > 0 {
                chooseImageView.backgroundColor = UIColor.cyan
                chooseLabel.text = "\(photo.chooseNumber)"
            } else {
                chooseImageView.backgroundColor = UIColor.clear
                chooseLabel.text = nil
            }
        }
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}

